<template>
  <view class="uni-container">
    <uni-forms ref="form" v-model="formData" validateTrigger="bind">
		<uni-forms-item name="class_id" label="教学班" required>
		  <input @input="binddata('class_id', $event.detail.value)" class="uni-input-border" :value="formData.class_id" placeholder="教学班标识唯一标识" />
		</uni-forms-item>
		<uni-forms-item name="number" label="人数" required>
		  <uni-easyinput placeholder="人数" type="number" v-model="formData.number" />
		</uni-forms-item>
		<uni-forms-item name="course" label="课程编码">
			<el-select style="width: 100%;" v-model="formData.course"
							filterable remote placeholder="请输入课程编码或课程名"
							:remote-method="searchCourse" :loading="courseLoading">
			   <el-option
			     v-for="item in formOptions.courseOptions"
			     :key="item.value"
			     :label="item.label"
			     :value="item.value">
			   </el-option>
			 </el-select>
		</uni-forms-item>
		<uni-forms-item name="username" label="教师工号/姓名">
			 <el-select style="width: 100%;" v-model="formData.username" :disabled="isTeacher"
				filterable remote placeholder="请输入教师工号或姓名"
				:remote-method="searchTeacher" :loading="teacherLoading">
			    <el-option
			      v-for="item in formOptions.teacherOptions"
			      :key="item.value"
			      :label="item.label"
			      :value="item.value">
			    </el-option>
			  </el-select>
		</uni-forms-item>
		<uni-forms-item name="day" label="星期">
			<el-select v-model="formData.day" placeholder="请选择" @change="handleChange" style="width: 100%;">
			  <el-option
			      v-for="item in formOptions.dayOptions"
			      :key="item.value"
			      :label="item.label"
			      :value="item.value">
			  </el-option>
			</el-select>
		</uni-forms-item>
		<uni-forms-item name="node" label="节次">
			<el-select v-model="formData.node" placeholder="请选择" @change="handleChange" style="width: 100%;">
			  <el-option
			      v-for="item in formOptions.nodeOptions"
			      :key="item.value"
			      :label="item.label"
			      :value="item.value">
			  </el-option>
			</el-select>
		</uni-forms-item>
		<uni-forms-item name="address" label="课室">
		  <el-cascader  v-model="formData.address" style="width: 100%;"
			:options="formOptions.classRoomOptions"
			:disabled="openRoom"></el-cascader>
		</uni-forms-item>
		<uni-forms-item name="start_week" label="开始周">
		  <uni-easyinput placeholder="开始周" v-model="formData.start_week" />
		</uni-forms-item>
		<uni-forms-item name="end_week" label="结束周">
		  <uni-easyinput placeholder="结束周" v-model="formData.end_week" />
		</uni-forms-item>
		<!-- <uni-forms-item name="biweekly" label="单双周">
		  <uni-data-checkbox v-model="formData.biweekly" :localdata="formOptions.biweekly_localdata" />
		</uni-forms-item> -->
		<!-- <uni-forms-item name="parent_id" label="大课标识">
		  <uni-easyinput placeholder="无小课填当前教学班标识" v-model="formData.parent_id" />
		</uni-forms-item> -->
		<uni-forms-item name="comment" label="备注">
		  <uni-easyinput type="textarea" placeholder="备注" v-model="formData.comment" />
		</uni-forms-item>

      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator url="/pages/course/teaching/list" style="margin-left: 15px;">
            <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '@/js_sdk/validator/teaching.js';
	import {mapState} from 'vuex'

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'teaching-class';

  function getValidator(fields) {
    let reuslt = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        reuslt[key] = validator[key]
      }
    }
    return reuslt
  }

  export default {
    data() {
      return {
				courseLoading: false,
				teacherLoading: false,
				openRoom : true ,
				isTeacher: false,
        formOptions: {
					courseOptions:[],
					teacherOptions:[],
					classRoomOptions:[],
					dayOptions: [{
						label: "周一",value: 1},{
						label: "周二",value: 2},{
						label: "周三",value: 3},{
						label: "周四",value: 4},{
						label: "周五",value: 5}],
					nodeOptions:[{
						label: "09:00-10:20",value: 1},{
						label: "10:40-12:00",value: 2},{
						label: "12:30-13:50",value: 3},{
						label: "14:00-15:20",value: 4},{
						label: "15:30-16:50",value: 5},{
						label: "17:00-18:20",value: 6},{
						label: "19:00-20:20",value: 7},{
						label: "20:30-21:50",value: 8}],
					"biweekly_localdata": [{
						"text": "单双周","value": 0},{
						"text": "单周"  ,"value": 1},{
						"text": "双周"  ,"value": 2}]
				},
				formData: {
					"class_id": "",
					"number": null,
					"course": "",
					"username":"",
					"week": "",
					"day": null,
					"node": null,
					"classroom": "",
					"address":[],
					"start_week": "",
					"end_week": "",
					"biweekly": 0,
					"parent_id": "",
					"comment": "",
					"roomSchedule":""
				},
        rules: {
          ...getValidator(["class_id","number","course","week","day","node","start_week","end_week","biweekly","parent_id","comment","roomSchedule"])
        }
      }
    },
		computed: {
			...mapState('user', ['userInfo']),
		},
    onReady() {
      this.$refs.form.setRules(this.rules)
			const { username, nickname, role } = this.userInfo
			if(role[0] === "TEACHER"){
				this.isTeacher = true
				this.formOptions.teacherOptions.push({value: username, label: `${username}－${nickname}` })
				this.formData.username = username
			}
			console.log(this.userInfo)
    },
    methods: {
      /**
       * 触发表单提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.submit().then((res) => {
          this.submitForm(res)
        }).catch((errors) => {
          uni.hideLoading()
        })
      },

      submitForm(value) {
        // 使用 uni-clientDB 提交数据
				value.day = value.day + ''
				value.node = value.node + ''
				value.parent_id = value.class_id
				value.course_id = value.course
				value.classroom = value.address[2]
				value.optionalNumber = value.number
				db.collection('classroomSchedule').add({
					room_name:value.classroom,
					day: value.day,
					node: value.node,
					teachingClass: value.class_id
				}).then((res)=>{
					value.roomSchedule = res.result.id
					db.collection(dbCollectionName).add(value).then((res) => {
					  uni.showToast({
					    title: '新增成功'
					  })
					  this.getOpenerEventChannel().emit('refreshData')
					  setTimeout(() => uni.navigateTo({
							url: '/pages/course/teaching/list'
						}), 500)
					}).catch((err) => {
					  uni.showModal({
					    content: err.message || '请求服务失败',
					    showCancel: false
					  })
					}).finally(() => {
					  uni.hideLoading()
					})
				})
      },
			
			// day或node修改触发课室修改
			handleChange() {
				let {day , node} = this.formData
				day && node && this.loadClassroom(day , node)
			},
			
			// 搜索课程
			async searchCourse(query){
				if (query !== '') {
					this.teacherLoading = true;
					await this.$request('teachingClass/searchCourse')
					.then((res)=>{
						this.teacherLoading = false;
						this.formOptions.courseOptions = res.filter(item => {
							return item.label.toLowerCase()
								.indexOf(query.toLowerCase()) > -1;
						});
					})
				} else {
					this.formOptions.courseOptions = [];
				}
			},
			
			// 搜索教师
			async searchTeacher(query) {
				if (query !== '') {
					this.teacherLoading = true;
					await this.$request('teachingClass/searchTeacher')
					.then((res)=>{
						this.teacherLoading = false;
						this.formOptions.teacherOptions = res.filter(item => {
							return item.label.toLowerCase()
								.indexOf(query.toLowerCase()) > -1;
						});
					})
				} else {
					this.formOptions.teacherOptions = [];
				}
			},
			
			// 获取空闲课室
			async loadClassroom(day , node){
				await this.$request('teachingClass/searchRoom',{day , node})
				.then((res)=>{
					console.log(res)
					this.formOptions.classRoomOptions = res
				}).finally(()=> this.$set(this,"openRoom",false));
			}
    }
  }
</script>

